// components/addr.js
var addrbill = require('../../../xc/model/shop_clubaddr.js')
var actmember = require('../../../xc/model/member')
var acttoolv2 = require('../../../xc/sys/toolv2')
var userlocationv2 = require('../../../xc/sys/location/userlocationv2')
var util = require('../../../utils/util');

const app = getApp()

Component({
  options: {
    addGlobalClass: true,
    multipleSlots: true
  },

  /**
   * 组件的属性列表
   */
  properties: {
    isshowselectd: { //是否可切换地址
      type: Boolean,
      value: true
    },
    xtid: { // 1社区团长点，2到店自提点
      type: Number,
      value: 1
    },
    showselected: { // 属性名
      type: Boolean,
      value: true
    },
    selectdefault: { // 属性名
      type: Boolean,
      value: true
    },
    delivery_config: {
      type: Object,
      value: {}
    },
    themcolor: {
      type: Object,
      value: {}
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    actid: -1, // 选中团长
    isshowpickuptime: false,
    // location:"请定位",
    addrmodel: {},
    region: [],
    addrblock: true,
    addrlist: [],
    op: "result",
    CustomBar: app.globalData.CustomBar,
    scroll: false,
    userset: {
      pickuptime: null,
      name: "",
      phone: "",
      clubdelivery: "0"
    },
    vildfield: {
      name: true,
      phone: true,
      pickuptime: true
    },
    pageshow: true,
    basicurl: app.globalData.basicurl,
    phoneallow: -1,
    showfeatchtime: 1,
    orderconfig: null,
    currentDate: new Date().getTime(),
  },
  ready: function () {
    if (app.globalData.configdata) {
      if (app.globalData.configdata.order) {
        this.setData({
          orderconfig: app.globalData.configdata.order
        })
        if (app.globalData.configdata.order.selffetchstatus) {
          this.setData({
            showfeatchtime: app.globalData.configdata.order.selffetchstatus
          })
        }
      }
      if (app.globalData.configdata.yihuo) {
        this.setData({
          yihuoconfig: app.globalData.configdata.yihuo
        })
      }
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    navto(e) {
      var clubid = e.currentTarget.dataset.clubid
      wx.navigateTo({
        url: '/xc_lshop/club/clubshop/index?clubid=' + clubid,
      })
    },
    chooseLocation(ev) {

      var address = this.selectComponent("#address");
      address.chooseLocation(ev)

    },

    chagestatus(val) {
      this.setData({
        pageshow: val
      })
      this.triggerEvent('selectchange', val)
    },
    vliduserset: function (field) {
      // var orderconfig=this.data.orderconfig;
      var updatemodel = {}
      if (field) {
        updatemodel['vildfield.' + field] = this.judgekey(field);
      } else {
        ["name", "phone", "pickuptime"].forEach(item => {
          updatemodel['vildfield.' + item] = this.judgekey(item);
        })
      }
      console.log("updatemodel")

      console.log(updatemodel)
      this.setData(updatemodel)
    },
    judgekey(key) {
      var orderconfig = this.data.orderconfig
      var status = -1;
      if (key == 'phone') {
        if (orderconfig && orderconfig.phonestatus == 1) {
          status = 1
        }
      } else if (key == 'name') {
        if (orderconfig && orderconfig.namestatus == 1) {
          status = 1
        }
      } else if (key == 'pickuptime') {
        if (orderconfig && orderconfig.selffetchstatusrequire == 1) {
          status = 1
        }
      }
      if (status == 1) {
        return app.globalData.userset[key] ? true : false;
      } else {
        return true
      }

    },
    inputname: function (e) {
      var dataset = e.target.dataset
      app.globalData.userset[dataset.field] = e.detail
      this.vliduserset(dataset.field)
    },
    //更新自取时间
    confirmdatetime: function (e) {

      var type = e.currentTarget.dataset.type
      var data = ""
      if (type == 'datetime') {
        var date = new Date(parseInt(e.detail));
        data = util.formatTime(date)
      } else {
        data = e.detail
      }


      app.globalData.userset.pickuptime = data
      var updatemodel = {
        isshowpickuptime: false
      }
      updatemodel["userset.pickuptime"] = data
      this.setData({
        isshowpickuptime: false,
        pickuptime: data
      })
      this.vliduserset('pickuptime')
    },
    canceldatetime: function (e) {
      this.setData({
        isshowpickuptime: false
      })
    },
    showpickertime: function () {
      this.setData({
        isshowpickuptime: !this.data.isshowpickuptime
      })
    },




    //底部下拉
    onReachBottom: function (e) {
      var that = this;
      var strwhere = {};
      if (app.globalData.lat && app.globalData.lng) {
        strwhere['lat'] = app.globalData.lat;
        strwhere['lng'] = app.globalData.lng;
      }
      strwhere['xtid'] = this.data.xtid;
      if (this.data.keyval) {
        strwhere['keyval'] = this.data.keyval;
      }
      this.getpagelist(that, -1, strwhere);
    },
    //监听input
    watchinput: function (e) {

      this.data.keyval = e.detail;
      var that = this;
      var strwhere = {};
      if (app.globalData.lat && app.globalData.lng) {
        strwhere['lat'] = app.globalData.lat;
        strwhere['lng'] = app.globalData.lng;
      }
      strwhere['xtid'] = this.data.xtid;
      strwhere['keyval'] = e.detail;

      this.getpagelist(that, 1, strwhere);
    },
    //列表
    getpagelist(that, rest, strwhere) {
      if (rest == 1) {
        that.setData({
          addrlist: []
        });
      }
      addrbill.offset(that, rest, strwhere).then(function (result) {
        var updatemdoel = {};

        if ((result["code"] == "over" && result["obj"]) || result["code"] == "loadmore") {
          if (rest == 1) {
            updatemdoel["addrlist"] = result["obj"]["modellist"];
          } else {
            if (result["obj"]["modellist"].length > 0) {
              updatemdoel["addrlist"] = that.data.addrlist.concat(result["obj"]["modellist"]);
            }
          }
        }
        that.setData(updatemdoel);
      })
      return;
    },
    //返回
    Backfunc(e) {
      this.setData({
        op: "result"
      });
      this.chagestatus(true)
    },
    choseaddr: function () {
      var that = this;
      acttoolv2.forcechooseLocation().then(function (resut) {
        if (resut["status"] == 1) {
          var addr = resut["obj"]
          var strwhere = {};
          strwhere['lat'] = addr.latitude;
          strwhere['lng'] = addr.longitude;
          strwhere['xtid'] = that.data.xtid;
          that.getpagelist(that, 1, strwhere)

          that.setData({
            op: "list",
            address: addr["address"],
            district: addr["xcaddr"][2] ? addr["xcaddr"][2] : ""
          })
          that.chagestatus(false);

        }


      })
    },
    //点击显示收货地址列表
    showselect: function (e) {
      if(this.data.selectaddr && this.data.selectaddr.id){
         if(this.data.orderconfig){
           var orderconfig=this.data.orderconfig;
           if(orderconfig['clubchangestatus']==-1){//禁止切换
               return false
               
           }
         }
      }
      console.log("this.data")

      console.log(this.data)
      var actid = -1
      if (e && e.currentTarget) {
        actid = e.currentTarget.dataset.actid
      }
      var that = this;
      this.setData({
        actid: actid,
        keyval: ""
      })

   
     
      this.getLocation();
    },
    // agree() {
    //   // 用户点击同意按钮后
    //   this.resolvePrivacyAuthorization({ buttonId: 'agree-btn', event: 'agree' })
    //   // 用户点击同意后，开发者调用 resolve({ buttonId: 'agree-btn', event: 'agree' })  告知平台用户已经同意，参数传同意按钮的id
    //   // 用户点击拒绝后，开发者调用 resolve({ event:'disagree' }) 告知平台用户已经拒绝
    // },
    // disagree(){
    //   this.resolvePrivacyAuthorization({event:'disagree' })
    // },
    getLocation: function () {
      var that = this;
      userlocationv2.lastaddr().then(function (resut) {
        console.log("lastaddr")
        console.log(resut)

        if (resut["status"] == 1) {
          var addr = resut["obj"]
          var strwhere = {};
          strwhere['lat'] = addr.lat;
          strwhere['lng'] = addr.lng;
          strwhere['xtid'] = that.data.xtid;
          that.getpagelist(that, 1, strwhere)

          that.setData({
            op: "list",
            address: addr["addrinfo"],
            district: addr["district"]
          })

          that.chagestatus(false);
        } else {

          that.choseaddr()
        }
        return;

      })
    },
    loadpage() {

    },

    setclubdeliveryaddr(clubdelivery) {


      this.setData({
        'userset.clubdelivery': clubdelivery
      })
      app.globalData.userset.clubdelivery = clubdelivery
      var that = this;
      if (clubdelivery == 2) {

        var delivery_config = this.data.delivery_config;


        delivery_config["intracity"]["lat"] = this.data['selectaddr']["lat"]
        delivery_config["intracity"]["lng"] = this.data['selectaddr']["lng"]
        setTimeout(function () {
          var address = that.selectComponent("#address");
          address.set_init(3, delivery_config, addr);
        }, 200)
      } else {
        this.triggerEvent("shopdelivery", {
          clubdelivery: "1"
        })

      }
    },
    /**
     * 
     * @param {*} ev 
     * @param {*} addr   //有地址的情况设定地址
     */
    clubdeliverychang(ev, addr) {

      this.setData({
        'userset.clubdelivery': ev.detail
      })
      var that = this;
      if (ev.detail == 2) {
        var delivery_config = this.data.delivery_config;

        delivery_config["intracity"]["lat"] = this.data['selectaddr']["lat"]
        delivery_config["intracity"]["lng"] = this.data['selectaddr']["lng"]


        setTimeout(function () {

          var address = that.selectComponent("#address");


          address.set_init(3, delivery_config, addr);
        }, 200)
      } else {
        this.triggerEvent("shopdelivery", {
          clubdelivery: "1"
        })
      }
    },
    //初始化
    set_init(xtid, clubdelivery, expressaddr) {
      // this.setData({
      //   'userset.clubdelivery':2
      // })

   
      var _that = this;
      var app = getApp()
      this.getmycloubinforesove().then(function (res) {
     
        var updatepara = {}
        if (xtid) {
          _that.data.xtid = xtid
          updatepara["xtid"] = xtid
        }
        var userset = {};
        
      
        if (app.globalData.member) {
          userset = app.globalData.userset
          var member = app.globalData.member
          if (!userset.phone && member.memberinfo && member.memberinfo.phone) {
            userset.phone = member.memberinfo.phone;
          }
          if (!userset.name && member.memberinfo) {
            userset.name = member.memberinfo.name;
          }
        }


        if (app.globalData && app.globalData.Custom) {
          updatepara["Custom"] = app.globalData.Custom
          updatepara["CustomBar"] = app.globalData.CustomBar


          if (_that.data.xtid == 2) {
          
            if (app.globalData.selectshop) {
              updatepara['selectaddr'] = app.globalData.selectshop
            } else if (_that.data.clubinfo && _that.data.clubinfo.autarky == 1) {
              updatepara['selectaddr'] = _that.data.clubinfo;
            } else {
              updatepara['selectaddr'] = null;
            }
          } else if (_that.data.xtid == 1) {
            if (app.globalData.selectclub) {
              updatepara['selectaddr'] = app.globalData.selectclub
            } else if (_that.data.clubinfo && _that.data.clubinfo.autarky == -1) {
              updatepara['selectaddr'] = _that.data.clubinfo
            } else {
              updatepara['selectaddr'] = null
            }
          }


          if (updatepara['selectaddr']) {

            _that.valideclub(updatepara['selectaddr']['id'], userset, updatepara, clubdelivery, expressaddr)
          } else {
       
            userset['clubdelivery'] = "0"
            userset['clubdelivery'] = userset['clubdelivery'] + ''
            updatepara['userset'] = userset
          }
       

           
         
        }
   
        _that.setData(updatepara);
      })

    },
    //获取手机号
    getPhoneNumber(e) {
      var that = this;
      var dataset = e.currentTarget.dataset;
      var encryptedData = e.detail.encryptedData;
      // if (!encryptedData) {

      //   return;
      // }
      var iv = e.detail.iv;
      var app = getApp();
      var code = e.detail.code;

      app.toolv2.getphone(encryptedData, iv, code).then(function (data) {

        if (data["code"] == "success") {
          var upatemodel = {};
          upatemodel["userset.phone"] = data["obj"].phoneNumber;
          app.globalData.userset.phone = upatemodel["userset.phone"]
          that.setData(upatemodel);
          that.vliduserset("phone")
        }
      });
    },
    selectaddrfunc(ev) {



      var obj = {
        clubdelivery: this.data.userset.clubdelivery,
        obj: ev.detail
      }
      this.triggerEvent("shopdelivery", obj)
    },
    //选择当前地址
    selecteditem(e) {

      var dataset = e.currentTarget.dataset;
      var selectaddr = this.data.addrlist[dataset["idx"]];

      var clubdelivery = "1"
      if (selectaddr["pickmethod"] == 2) {
        clubdelivery = "2"
      } else {
        clubdelivery = "1"

      }
      this.setData({
        'userset.clubdelivery': clubdelivery
      })
      var app = getApp();
      if (this.data.xtid == 1) {
        app.globalData.selectclub = selectaddr;
      } else if (this.data.xtid == 2) {
        app.globalData.selectshop = selectaddr;
      }
      this.setData({
        selectaddr: selectaddr,
        op: "result",
      })
      this.chagestatus(true)

      this.triggerEvent("selectgroupaddr", selectaddr)
      this.clubdeliverychang({
        detail: clubdelivery
      })
    },

    scroll: function (e) {

      if (e.detail.scrollTop > 100) {
        this.setData({
          scroll: true
        })
      } else {
        this.setData({
          scroll: false
        })
      }
    },
    //验证团是否有效
    valideclub(clubid, userset, updatepara, clubdelivery, expressaddr) {
      var that = this;
      addrbill.getmodel(clubid).then(res => {
        if (res.status == 1) {
          var obj = res.obj;


          if (obj['status'] == 1 && obj['islock'] == -1) {
            if (updatepara['selectaddr']["pickmethod"] == 2) {

              userset['clubdelivery'] = "2"
              var delivery_config = this.data.delivery_config;
              delivery_config["intracity"]["lat"] = updatepara['selectaddr']["lat"]
              delivery_config["intracity"]["lng"] = updatepara['selectaddr']["lng"]
              updatepara["delivery_config.intracity.lat"] = updatepara['selectaddr']["lat"]
              updatepara["delivery_config.intracity.lng"] = updatepara['selectaddr']["lng"]

              setTimeout(function () {

                var address = that.selectComponent("#address");
                address.set_init(3, delivery_config);
              }, 200)

            } else if (updatepara['selectaddr']["pickmethod"] == 3 && clubdelivery) {

              userset['clubdelivery'] = clubdelivery
            } else {

              userset['clubdelivery'] = "1"
            }
            that.data.selectaddr = updatepara['selectaddr']

            that.clubdeliverychang({
              detail: userset["clubdelivery"],
              expressaddr
            })
            that.triggerEvent("selectgroupaddr", updatepara['selectaddr'])
          } else {
            updatepara['selectaddr'] = null
            userset['clubdelivery'] = "0"

          }
          userset['clubdelivery'] = userset['clubdelivery'] + ''
          updatepara['userset'] = userset
          that.setData(updatepara);
          // that.setData({ xcmodel: res.obj }) 
        } else {
          updatepara['selectaddr'] = null

          userset['clubdelivery'] = "0"
          userset['clubdelivery'] = userset['clubdelivery'] + ''
          updatepara['userset'] = userset
          that.setData(updatepara);
        }
      })
    },
    getmycloubinfo() {

      var app = getApp()
      if (app.globalData.clubinfo) {
        this.setData({
          clubinfo: app.globalData.clubinfo
        })
      } else {
        actmember.getmycloubinfo().then(res => {
          if (res["status"] == 1) {
            var clubinfo = res["obj"]
            if (app.globalData.lng) {
              var preslut = acttoolv2.distanceByLnglat(app.globalData.lng, app.globalData.lat, clubinfo.lng, clubinfo.lat)
              clubinfo["juli"] = preslut["formatval"] + preslut["unit"];
            }

            app.globalData.clubinfo = clubinfo;
            console.log("iiii")
            console.log(clubinfo)

            this.setData({
              clubinfo: clubinfo
            })
          }
        })
      }

    },
    getmycloubinforesove() {
      var that = this
      return new Promise(function (resolve) {
      
        var app = getApp()
        if (app.globalData.clubinfo) {

          that.setData({
            clubinfo: app.globalData.clubinfo
          })
          resolve(app.globalData.clubinfo)
        } else {

          actmember.getmycloubinfo().then(res => {
      
            if (res["status"] == 1) {
     
              var clubinfo = res["obj"]
              if (app.globalData.lng) {
                var preslut = acttoolv2.distanceByLnglat(app.globalData.lng, app.globalData.lat, clubinfo.lng, clubinfo.lat)
                clubinfo["juli"] = preslut["formatval"] + preslut["unit"];
              }

              app.globalData.clubinfo = clubinfo;
        
              that.setData({
                clubinfo: clubinfo
              })
              resolve(clubinfo)

            }else{
     
              resolve({status:-1})
            }
          })
        }
      });
    },
  }
})